/*
 * $Id$
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.googlecode.jasperlib;

import javax.servlet.Servlet;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.HttpJspPage;

import com.googlecode.jasperlib.internal.ServletCache;

import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Maintains a cache of jsp locations -> servlet instances for those jsps. When
 * a jsp is requested from the cache, the cache will block if the jsp was not
 * compiled already, and wait for the compilation
 */
public abstract class JSPRuntime {
    // maps from jsp path -> pagelet
    protected static final ServletCache servletCache = new ServletCache();
    
    public final static String CLASS_LOADER_INTERFACE_ATTR = "__JSPRuntime.ClassLoaderInterface_";
    public final static String ADDITIONAL_JARS_ATTR = "__JSPRuntime.AdditionalJars_";
    public final static String TLD_LOCATIONS_CACHE_FACTORY = "__JSPRuntime.TldLocationsCacheFactory_";
    public final static String MEMORY_CLASS_LOADER_ATTR = "__JSPRuntime.MemoryClassLoader_";

    public static void clearCache() {
        servletCache.clear();
    }

    public static void handle(String location, HttpServletRequest request, HttpServletResponse response, boolean flush,
                              ClassLoaderInterface classLoaderInterface, List<URL> additionalJars,
                              TldLocationsCacheFactory tldLocationsCacheFactory, MemoryClassLoader targetClassLoader, ServletContext servletContext) throws Exception {
        HashMap<String, Object> attributes = new HashMap<String, Object>();
        Enumeration attributeNames = servletContext.getAttributeNames();
        while(attributeNames.hasMoreElements()) {
            String name = (String) attributeNames.nextElement();
            attributes.put(name, servletContext.getAttribute(name));
        }
        handle(location, request, response, false, null, null, null, targetClassLoader, attributes);
    }

    public static void handle(String location, HttpServletRequest request, HttpServletResponse response, boolean flush,
            ClassLoaderInterface classLoaderInterface, List<URL> additionalJars,
            TldLocationsCacheFactory tldLocationsCacheFactory, MemoryClassLoader targetClassLoader, Map<String, Object> servletContextAttributes) throws Exception {
        if (targetClassLoader == null)
            throw new IllegalArgumentException("MemoryClassLoader parameter cannot be null");
        
        request.setAttribute(CLASS_LOADER_INTERFACE_ATTR, classLoaderInterface);
        request.setAttribute(ADDITIONAL_JARS_ATTR, additionalJars);
        request.setAttribute(TLD_LOCATIONS_CACHE_FACTORY, tldLocationsCacheFactory);
        request.setAttribute(MEMORY_CLASS_LOADER_ATTR, targetClassLoader);

        location = org.apache.commons.lang.StringUtils.substringBefore(location, "?");

        if (classLoaderInterface == null)
            classLoaderInterface = new ClassLoaderInterfaceDelegate(JSPRuntime.class.getClassLoader());

        Servlet servlet = servletCache.get(location, classLoaderInterface, additionalJars, tldLocationsCacheFactory,
                targetClassLoader, servletContextAttributes);
        HttpJspPage page = (HttpJspPage) servlet;

        page._jspService(request, response);
        if (flush)
            response.flushBuffer();
    }
}
